// https://zhuanlan.zhihu.com/p/137914574
#include <iostream>
#include <mutex>
#include <thread>
#include <chrono>

std::mutex _mtx;

void mutexfunc()
{
    auto func = [](int k)
    {
        _mtx.lock();
        for (int i = 0; i < k; i++)
        {
            std::cout << i << " ";
        }
        std::cout << std::endl;
        _mtx.unlock();
    };
    std::thread threads[5];
    for (int i = 0; i < 5; i++)
    {
        threads[i] = std::thread(func, 200);
    }
    for (auto &th : threads)
    {
        th.join();
    }
}

std::timed_mutex _timedmtx;

void timedmutexfunc()
{
    auto func = [](int k)
    {
        for (int i = 0; i < k; i++)
        {
            if (_timedmtx.try_lock_for(std::chrono::milliseconds(2)))
            {
                std::cout << k << " " << i << "\n";
                _mtx.unlock();
            }
            else
            {
                std::cout << k << " try_lock_for " << i << " failed\n";
            }
        }
    };
    std::thread threads[5];
    for (int i = 0; i < 2; i++)
    {
        threads[i] = std::thread(func, i + 10);
    }
    for (auto &th : threads)
    {
        th.join();
    }
}

int main(int argc, char const *argv[])
{
    // mutexfunc();
    timedmutexfunc();
    return 0;
}
